class Game {
  constructor() {
    this.gameList = {};
  }

  create(room){
    // 查看在gamelist中是否存在这个房间的游戏
    if(this.gameList[room.key]){
      // 如果已经存在了，就将这个房间销毁
      global.Core.socket.system('房间冲突。房间销毁，游戏实例销毁', 'red', null, room.key);
      global.Core.room.destroy(room.key);
      this.destroy(room.key)
      return;
    }

    this.gameList[room.key] = new G(room);
    global.Core.socket.system('游戏创建成功', 'green', null, room.key);
    room.isGame = true;

    // 发送游戏提示
    this.sendInfo(room.key);
  }

  async sendInfo(key){
    global.Core.socket.system('游戏现在为自由移动，10秒钟后进入对战。', 'green', null, key);
    await global.Core.util.delay(7000);
    global.Core.socket.system('距离游戏开始还有3秒', 'green', null, key);
    await global.Core.util.delay(1000);
    global.Core.socket.system('距离游戏开始还有2秒', 'yellow', null, key);
    await global.Core.util.delay(1000);
    global.Core.socket.system('距离游戏开始还有1秒', 'red', null, key);
    await global.Core.util.delay(1000);
    global.Core.socket.system('游戏开始！用你的身体去冲击别人的肉体吧，血腥开始啦，嗷呜！', 'white', null, key);
    this.startGame(key);
  }

  action(player, action){
    this.gameList[player.data.room].actions[player.socket.id].push(action);
  }

  startGame(key){

  }

  destroy(key){

  }
}

class G{
  constructor(room){
    this.room = room;
    this.frames = [];
    this.actions = {};
    this.packageNum = global.option.gameFrame;
    this.interval = null;
    this.step = 'move';

    // 将房间内所有人置入游戏中;
    this.sendPlayer();
    this.start();
  }

  sendPlayer(){
    // 给每个玩家设置不同的颜色 并且将在实例上加上对应玩家存储操作的数组
    this.room.playerList.forEach(item => {
      global.Core.player.get(item.id).set('color', `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`);
      this.actions[item.id] = [];
    });
    global.Core.socket.emit('game.start', {
      room: this.room,
      game: {
        packageNum: this.packageNum,
        step: this.step
      }
    }, null, this.room.key);
  }

  start(){
    this.interval = setInterval(() => {
      // 将房间中所有玩家的动作统一发送给房间内所有人
      global.Core.socket.emit('game.action', this.actions, null, this.room.key);
      this.frames.push(this.actions);
      this.room.playerList.forEach(item => {
        this.actions[item.id] = [];
      });
    }, 1000 / this.packageNum);
  }
}

module.exports = Game;